<template>
  <div class="container">
    <el-form ref="ruleForm" :model="query" :rules="rules" label-width="120px">
      <el-form-item label="消息标题" prop="noticeTitle">
        <el-input
          v-model="query.noticeTitle"
          placeholder="请输入消息标题"
        ></el-input>
      </el-form-item>
      <el-form-item label="单位业态" prop="bodyIndustry">
        <div class="checkbox">
          <el-checkbox
            class="checkbox_last"
            v-model="bodyIndustryAll"
            label="全选"
            name="type"
            @change="onCheckboxBodyIndustry"
          ></el-checkbox>
          <el-checkbox-group
            v-model="query.bodyIndustry"
            @change="onCheckboxGroupBodyIndustry"
          >
            <el-checkbox
              :label="item.bodyIndustryRemarks"
              name="type"
              v-for="item in query.bodyIndustryList"
              :key="item.id"
            ></el-checkbox>
          </el-checkbox-group>
        </div>
      </el-form-item>
      <el-form-item label="区域" prop="area">
        <div class="checkbox">
          <el-checkbox
            class="checkbox_last"
            v-model="areaAll"
            label="全选"
            @change="onCheckbox"
          ></el-checkbox>
          <el-checkbox-group v-model="query.area" @change="onCheckboxGroup">
            <el-checkbox
              :label="item.areaName"
              v-for="item in query.areaList"
              :key="item.areaCode"
            ></el-checkbox>
          </el-checkbox-group>
        </div>
      </el-form-item>

      <el-form-item label="人员类型" prop="type">
        <div class="checkbox">
          <el-checkbox
            class="checkbox_last"
            v-model="typeAll"
            label="全选"
            @change="onChecktype"
          ></el-checkbox>
          <el-checkbox-group v-model="query.type" @change="ontypeGroup">
            <el-checkbox
              :label="item.name"
              v-for="item in query.typeList"
              :key="item.code"
            ></el-checkbox>
          </el-checkbox-group>
        </div>
      </el-form-item>
      <el-form-item label="消息内容" prop="noticeContent">
        <quill-editor
          :content="query.noticeContent"
          :options="editorOption"
          @change="onEditorChange($event)"
        />
      </el-form-item>
      <el-form-item label="相关附件">
        <el-upload
          :file-list="query.unitNoticeMessageFileSaveRequestList"
          drag
          :action="$upload"
            :headers="$headers()"
          :on-preview="
            (e) => {
              $downloadFiles(e.fileUrl);
            }
          "
          :on-error="onError"
          :on-remove="onRemove"
          :before-remove="beforeRemove"
          multiple
          :on-success="success"
          :before-upload="
            (e) => {
              return $beforeAvatarUpload(e,1);
            }
          "
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">
            只能上传world、excel、pdf文件，且不超过5M
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item label="">
        <div class="form_button">
          <el-button type="primary" @click="submit(0)">仅保存</el-button>
          <el-button type="primary" @click="submit(1)">保存并下发</el-button>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { quillRedefine } from "vue-quill-editor-upload";
export default {
  created() {
    let data = JSON.parse(sessionStorage.getItem('message'));
    this.query.releaseDate=this.$moment().format('YYYY-MM-DD')
    if (data) {
      this.query.releaseDate = data.releaseDateStr;
      this.query.createUnitId = data.createUnitId;
      this.query.createUnitName = data.createUnitName;
      this.query.id = data.id;
      this.query.releaseState = data.releaseState;
      this.query.noticeSource = data.noticeSource;
      this.query.noticeContent = data.noticeContent;
      this.query.noticeTitle = data.noticeTitle;
      this.query.area = data.unitNoticeMessageAreaResponseList.map(
        x => x.areaName
      );
      this.query.bodyIndustry = data.unitNoticeMessageFormatResponseList.map(
        x => x.bodyIndustryAndBodyIndustryRemarks
      );
      this.query.type = data.unitNoticeMessageTypeResponseList.map(
           x => x.typeName
      );
      data.unitNoticeMessageFileResponseList.forEach(x => {
        x.name = x.fileName;
      });

this.query.unitNoticeMessageFileSaveRequestList=data.unitNoticeMessageFileResponseList

     if (
              this.query.type.length ==
              this.query.typeList.length
            ) {
              this.typeAll = true;
            }


    }
        this.findListNoParentByParentCode();
    this.getModulesCate();
    let that = this;
    this.editorOption = quillRedefine({
      // 图片上传的设置
      uploadConfig: {
        action: that.$upload, // 必填参数 图片上传地址
        // 必选参数  res是一个函数，函数接收的response为上传成功时服务器返回的数据
        // 你必须把返回的数据中所包含的图片地址 return 回去
        res: (respnse) => {
          if (respnse.code == 200) {
            return that.$uploadURL + respnse.data;
          } else {
            that.$error("上传失败");
          }
        },
        methods: "POST", // 可选参数 图片上传方式  默认为post
        token: "", // 可选参数 如果需要token验证，假设你的token有存放在sessionStorage
        name: "file", // 可选参数 文件的参数名 默认为img
        size: 5 * 1024, // 可选参数   图片限制大小，单位为Kb, 1M = 1024Kb
        accept: "image/png,  image/jpeg, ", // 可选参数 可上传的图片格式
        // start: function (){}
        start: (e) => {}, // 可选参数 接收一个函数 开始上传数据时会触发
        end: (e) => {}, // 可选参数 接收一个函数 上传数据完成（成功或者失败）时会触发
        success: (e) => {}, // 可选参数 接收一个函数 上传数据成功时会触发
        error: () => {}, // 可选参数 接收一个函数 上传数据中断时会触发
      },
      // 以下所有设置都和vue-quill-editor本身所对应
      placeholder: "请输入编辑文章内容", // 可选参数 富文本框内的提示语
      theme: "", // 可选参数 富文本编辑器的风格
      toolOptions: [
        ["bold", "italic", "underline", "strike"],
        ["blockquote", "code-block"],
        [{ header: 1 }, { header: 2 }],
        [{ list: "ordered" }, { list: "bullet" }],
        [{ script: "sub" }, { script: "super" }],
        [{ indent: "-1" }, { indent: "+1" }],
        [{ direction: "rtl" }],
        [{ size: ["small", false, "large", "huge"] }],
        [{ header: [1, 2, 3, 4, 5, 6, false] }],
        [{ color: [] }, { background: [] }],
        [{ font: [] }],
        [{ align: [] }],
        ["clean"],
        ["link", "image"],
      ], // 可选参数  选择工具栏的需要哪些功能  默认是全部
      handlers: {},
    });
  },
  data() {
    return {
      form: {
        name: "",
        type: [],
      },
      content: "",
      editorOption: {},
      query: {
        releaseDate:"",
        createUnitId: "12515115144224",
        createUnitName: "苏州亿通",
        id: "",
        releaseState: 0,
        remark: "",
        noticeContent: "",
        noticeSource: "苏州市市场监督管理局",
        noticeTitle: "",
        releasePeople: "测试",
        releaseUnitName: "苏州市市场监督管理局",
        areaList: [],
        area: [],
        unitNoticeMessageAreaSaveRequestList: [],
        unitNoticeMessageFileSaveRequestList: [],
        unitNoticeMessageFormatSaveRequestList: [],
        unitNoticeMessageTypeSaveRequestList: [],
        bodyIndustryList: [],
        bodyIndustry: [],
        unitNumber: 0,
        type: [],
        typeList: [
          {
            name: "企业安全管理员",
            code: 1,
          },
          {
            name: "食品安全管理员",
            code: 2,
          },
          {
            name: "从业人员",
            code: 3,
          },
        ],
      },
      typeAll: false,
      bodyIndustryAll: false,
      areaAll: false,
      rules: {
        noticeTitle: [
          { required: true, message: "请输入任务名称", trigger: "blur" },
        ],
        bodyIndustry: [
          {
            type: "array",
            required: true,
            message: "请至少选择一个单位业态",
            trigger: "blur",
          },
        ],
        area: [
          {
            type: "array",
            required: true,
            message: "请至少选择一个区域",
            trigger: "blur",
          },
        ],
        type: [
          {
            type: "array",
            required: true,
            message: "请至少选择一个类别",
            trigger: "blur",
          },
        ],
        noticeContent: [
          {
            required: true,
            message: "请输入任务内容",
            trigger: "blur",
          },
        ],
      },
      pickerOptions: {
        disabledDate(time) {
           return time.getTime() <= Date.now()-60*60*1000*24;
        },
      },
    };
  },
  methods: {
    onEditorChange(e) {
      // console.log(e);
      this.query.noticeContent = e.html;
    },
    findListNoParentByParentCode() {
      this.$http
        .findListNoParentByParentCode({})
        .then((res) => {
          if (res.code == 200) {
            this.query.areaList = res.data;
            // this.onCheckbox(true);
            // this.areaAll = true;
            if (this.query.area.length == this.query.areaList.length) {
              this.areaAll = true;
            }
          } else {
            this.$error(res.msg);
          }
        })
        .catch((err) => {
          this.$error();
          console.log(err);
        });
    },
    onCheckbox(e) {
      if (e) {
        this.query.area = this.query.areaList.map((x) => x.areaName);
      } else {
        this.query.area = [];
      }
    },
    onChecktype(e) {
      if (e) {
        this.query.type = this.query.typeList.map((x) => x.name);
      } else {
        this.query.type = [];
      }
    },
    onCheckboxBodyIndustry(e) {
      if (e) {
        this.query.bodyIndustry = this.query.bodyIndustryList.map(
          (x) => x.bodyIndustryRemarks
        );
      } else {
        this.query.bodyIndustry = [];
      }
    },
    onCheckboxGroup(e) {
      if (e.length == this.query.areaList.length) {
        this.areaAll = true;
      } else {
        this.areaAll = false;
      }
    },
    ontypeGroup(e) {
      if (e.length == this.query.typeList.length) {
        this.typeAll = true;
      } else {
        this.typeAll = false;
      }
    },
    onCheckboxGroupBodyIndustry(e) {
      if (e.length == this.query.bodyIndustryList.length) {
        this.bodyIndustryAll = true;
      } else {
        this.bodyIndustryAll = false;
      }
    },
    success(e) {
      if (e.code == 200) {
        this.query.unitNoticeMessageFileSaveRequestList.push({
          name: this.$imageName,
          fileName: this.$imageName,
          fileUrl: this.$uploadURL + e.data,
          url: this.$uploadURL + e.data,
        });
      }
    },
    onError() {
      this.$error("上传失败");
    },
    onRemove(e) {
      this.query.unitNoticeMessageFileSaveRequestList =
        this.query.unitNoticeMessageFileSaveRequestList.filter(
          (x) => x.uid != e.uid
        );
    },
    beforeRemove(file) {
      if (file && file.status === "success") {
        return this.$confirm("确定删除这个文件吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });
      }
    },
    submit(type) {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          this.query.releaseState = type;
          this.query.unitNoticeMessageAreaSaveRequestList = [];
          this.query.unitNoticeMessageFormatSaveRequestList = [];
           this.query.unitNoticeMessageTypeSaveRequestList=[]
          this.query.areaList.forEach((x) => {
            if (this.query.area.includes(x.areaName)) {
              this.query.unitNoticeMessageAreaSaveRequestList.push({
                areaCode: x.areaCode,
                areaName: x.areaName,
              });
            }
          });
          this.query.bodyIndustryList.forEach((x) => {
            if (this.query.bodyIndustry.includes(x.bodyIndustryRemarks)) {
              this.query.unitNoticeMessageFormatSaveRequestList.push({
                bodyIndustry: x.bodyIndustry,
                bodyIndustryRemarks: x.bodyIndustryRemarks,
                isSpecialFood: x.isSpecialFood,
              });
            }
          });
          this.query.typeList.forEach((x) => {
            if (this.query.type.includes(x.name)) {
              this.query.unitNoticeMessageTypeSaveRequestList.push({
                typeCode: x.code,
                typeName: x.name,
              });
            }
          });
          this.$http
            .saveUnitNoticeMessage(this.query)
            .then((res) => {
              if (res.code == 200) {
                this.$success("保存成功");
                this.$router.push("/message");
              } else {
                this.$error(res.msg);
              }
            })
            .catch((err) => {
              console.log(err);
              this.$error();
            });
        } else {
          this.$error("请输入必填项");
        }
      });
    },
    getModulesCate() {
      this.$http
        .getModulesCate({
          isPage: 1,
          isOpen: 1,
          searchValue: "餐饮服务经营者",
          //           isSpecialFood: this.$route.query.isSpecialFood,
          isSpecialFood: 0,
        })
        .then((res) => {
          if (res.code == 200) {
            this.query.bodyIndustryList = res.data;
            // this.onCheckboxBodyIndustry(true);
            // this.bodyIndustryAll = true;
            // query.bodyIndustry
            if (
              this.query.bodyIndustry.length ==
              this.query.bodyIndustryList.length
            ) {
              this.bodyIndustryAll = true;
            }
          } else {
            this.$error(res.msg);
          }
        })
        .catch((err) => {
          this.$error();
          console.log(err);
        });
    },
  },
  // 监听属性
  watch: {},
  //实例销毁之前
  beforeDestroy() {
    sessionStorage.removeItem("viewTask");
  },
};
// query.area
</script>
<style lang="less" scoped>
.container {
  padding: 20px;
  .checkbox {
    display: flex;
    .checkbox_last {
      margin-right: 15px;
    }
  }
  .form_button {
    text-align: right;
  }
}
</style>
